package com.hig.risk.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.hig.risk.domain.RiskHazardSource;
import com.hig.risk.mapper.RiskHazardSourceMapper;
import com.hig.risk.service.IRiskHazardSourceService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import org.aspectj.weaver.ast.Not;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hig.risk.mapper.RiskScoreControlMapper;
import com.hig.risk.domain.RiskScoreControl;
import com.hig.risk.service.IRiskScoreControlService;

/**
 * 风险、危险源识别评分及控制Service业务层处理
 * 
 * @author scp
 * @date 2024-09-25
 */
@Service
public class RiskScoreControlServiceImpl implements IRiskScoreControlService 
{
    @Autowired
    private RiskScoreControlMapper riskScoreControlMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IRiskHazardSourceService riskHazardSourceService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private RiskHazardSourceMapper riskHazardSourceMapper;

    /**
     * 查询风险、危险源识别评分及控制
     * 
     * @param id 风险、危险源识别评分及控制ID
     * @return 风险、危险源识别评分及控制
     */
    @Override
    public RiskScoreControl selectRiskScoreControlById(Long id)
    {
        RiskScoreControl riskScoreControl = riskScoreControlMapper.selectRiskScoreControlById(id);
        if (riskScoreControl != null && StringUtils.isNotEmpty(riskScoreControl.getHazardsType())){
            String[] hazardsTypes = riskScoreControl.getHazardsType().split(",");
            riskScoreControl.setHazardsTypes(hazardsTypes);
        }
        return riskScoreControl;
    }

    /**
     * 查询风险、危险源识别评分及控制列表
     * 
     * @param riskScoreControl 风险、危险源识别评分及控制
     * @return 风险、危险源识别评分及控制
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<RiskScoreControl> selectRiskScoreControlList(RiskScoreControl riskScoreControl)
    {
        return riskScoreControlMapper.selectRiskScoreControlList(riskScoreControl);
    }

    /**
     * 新增风险、危险源识别评分及控制
     * 
     * @param riskScoreControl 风险、危险源识别评分及控制
     * @return 结果
     */
    @Override
    public int insertRiskScoreControl(RiskScoreControl riskScoreControl)
    {
        try {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        riskScoreControl.setCreateBy(loginUser.getUser().getUserName());
        riskScoreControl.setDeptId(loginUser.getUser().getDeptId());
        riskScoreControl.setCreateTime(DateUtils.getNowDate());
        String[] hazardsTypes = riskScoreControl.getHazardsTypes();
        String hazardsType = String.join(",", Arrays.stream(hazardsTypes)
                .map(String::valueOf)
                .toArray(String[]::new));
        riskScoreControl.setHazardsType(hazardsType);
        RiskHazardSource source = riskHazardSourceMapper.selectRiskHazardSourceById(riskScoreControl.getSourceId());
        if (source != null) {
            Date controlTime = riskScoreControl.getRevisionTime();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String revisionTime = dateFormat.format(controlTime);
            if (source.getRemarkSpare2() != null) {
                Date remarkSpare2 = dateFormat.parse(source.getRemarkSpare2());
                if (remarkSpare2.before(controlTime)) {
                    RiskHazardSource temp = new RiskHazardSource();
                    temp.setId(riskScoreControl.getSourceId());
                    temp.setRemarkSpare2(revisionTime);
                    riskHazardSourceMapper.updateRiskHazardSource(temp);
                }

            }else {
                RiskHazardSource temp = new RiskHazardSource();
                temp.setId(riskScoreControl.getSourceId());
                temp.setRemarkSpare2(revisionTime);
                riskHazardSourceMapper.updateRiskHazardSource(temp);
            }
        }
        return riskScoreControlMapper.insertRiskScoreControl(riskScoreControl);

        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 修改风险、危险源识别评分及控制
     * 
     * @param riskScoreControl 风险、危险源识别评分及控制
     * @return 结果
     */
    @Override
    public int updateRiskScoreControl(RiskScoreControl riskScoreControl)
    {
        try {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        riskScoreControl.setUpdateBy(loginUser.getUser().getUserName());
        riskScoreControl.setUpdateTime(DateUtils.getNowDate());
        String[] hazardsTypes = riskScoreControl.getHazardsTypes();
        String hazardsType = String.join(",", Arrays.stream(hazardsTypes)
                .map(String::valueOf)
                .toArray(String[]::new));
        riskScoreControl.setHazardsType(hazardsType);
        RiskHazardSource source = riskHazardSourceMapper.selectRiskHazardSourceById(riskScoreControl.getSourceId());
        if (source != null) {
            Date controlTime = riskScoreControl.getRevisionTime();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String revisionTime = dateFormat.format(controlTime);
            if (source.getRemarkSpare2() != null) {
                Date remarkSpare2 = dateFormat.parse(source.getRemarkSpare2());
                if (remarkSpare2.before(controlTime)) {
                    RiskHazardSource temp = new RiskHazardSource();
                    temp.setId(riskScoreControl.getSourceId());
                    temp.setRemarkSpare2(revisionTime);
                    riskHazardSourceMapper.updateRiskHazardSource(temp);
                }
            }else {
                RiskHazardSource temp = new RiskHazardSource();
                temp.setId(riskScoreControl.getSourceId());
                temp.setRemarkSpare2(revisionTime);
                riskHazardSourceMapper.updateRiskHazardSource(temp);
            }
        }
        return riskScoreControlMapper.updateRiskScoreControl(riskScoreControl);
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 批量删除风险、危险源识别评分及控制
     * 
     * @param ids 需要删除的风险、危险源识别评分及控制ID
     * @return 结果
     */
    @Override
    public int deleteRiskScoreControlByIds(Long[] ids)
    {
        return riskScoreControlMapper.deleteRiskScoreControlByIds(ids);
    }

    /**
     * 删除风险、危险源识别评分及控制信息
     * 
     * @param id 风险、危险源识别评分及控制ID
     * @return 结果
     */
    @Override
    public int deleteRiskScoreControlById(Long id)
    {
        return riskScoreControlMapper.deleteRiskScoreControlById(id);
    }

    @Override
    @DataScope(deptAlias = "d")
    public AjaxResult selectOvertime(RiskScoreControl control ) {
        String notEntered = "";
        String overtime = "";
        //查询所有危险源
        RiskHazardSource riskHazardSource = new RiskHazardSource();
        List<RiskHazardSource> list = riskHazardSourceService.selectSourceAll(riskHazardSource);
        String warningDaysKey = configService.selectConfigByKey("control.warning.days");
        long warningDays = Long.parseLong(warningDaysKey);
        for (RiskHazardSource source : list) {
            //查询修订时间最晚的
            control.setSourceId(source.getId());
            RiskScoreControl riskScoreControl = riskScoreControlMapper.selectOvertime(control);
            if (riskScoreControl !=null ){
                Date revisionTime = riskScoreControl.getRevisionTime();
                LocalDate productionDate = revisionTime.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate();
                LocalDate today = LocalDate.now();
                long daysSinceProduction = ChronoUnit.DAYS.between(productionDate, today);
                if (daysSinceProduction >= warningDays){
                    overtime += source.getHazardName() + ",";
                }
            }else {
                notEntered += source.getHazardName() + ",";
            }
        }
        String msg = "";
        if (overtime.length()>0){
            overtime = overtime.substring(0,overtime.length()-1);
            msg += overtime + "超过30天未修改，请添加新的风险数据！";
        }
        if (notEntered.length()>0){
            notEntered = notEntered.substring(0,notEntered.length()-1);
            msg += notEntered + "未录入，请添加新的风险数据！";
        }
        if (msg.length()>0){
            return AjaxResult.error(msg);
        }
        return AjaxResult.success();
    }

    @Override
    @DataScope(deptAlias = "d")
    public RiskScoreControl selectNewRevisionTime(RiskScoreControl riskScoreControl)
    {
        return riskScoreControlMapper.selectNewRevisionTime(riskScoreControl);
    }
}
